import { ref } from "vue";
import { cloneDeep } from "lodash-es";

/**
 * 操作历史
 */
export function useOperationHistory() {
  const undoStacks = ref<any[]>([]);
  const redoStacks = ref<any[]>([]);

  const maxStacks = 10;

  const execute = (operation: any) => {
    undoStacks.value.push(cloneDeep(operation));
    if (undoStacks.value.length > maxStacks) {
      undoStacks.value.shift(); // 超过最大步数时，移除最早的操作
    }
    redoStacks.value = []; // 新操作执行时，清空redo栈
  };

  // 撤销上一步操作
  const undo = (currentOperation: any) => {
    if (undoStacks.value.length === 0) {
      return null;
    }
    const operation = undoStacks.value.pop();
    redoStacks.value.push(cloneDeep(currentOperation));
    return operation;
  };

  // 重做上一步被撤销的操作
  const redo = (currentOperation: any) => {
    if (redoStacks.value.length === 0) {
      return null;
    }
    const operation = redoStacks.value.pop();
    undoStacks.value.push(cloneDeep(currentOperation));
    return operation;
  };

  return {
    undoStacks,
    redoStacks,
    execute,
    undo,
    redo
  };
}

export const operationHistory = useOperationHistory();
